/**
 * Notes: PLM项目业务逻辑
 * Ver : CCMiniCloud Framework 2.0.1 ALL RIGHTS RESERVED BY cclinux0730 (wechat)
 * Date: 2022-05-22 07:48:00 
 */

// 兼容性导出：此模块同时支持作为plm_biz和plm_service使用
module.exports.default = module.exports;

/**
 * PLM业务逻辑类
 * @description 提供PLM相关的业务逻辑方法
 */

// 导入工具类和依赖
const helpers = require('../config/project_helpers_config');
const timeHelper = helpers.timeHelper;
const dataHelper = helpers.dataHelper;
const pageHelper = helpers.pageHelper;
const cloudHelper = helpers.cloudHelper;
const cacheHelper = helpers.cacheHelper;

// 使用store配置文件
let plmStore;
try {
  const storeConfig = require('../config/store_config');
  plmStore = storeConfig.plmStore;
  console.log('加载PLM Store成功');
} catch (e) {
  console.error('加载PLM Store失败:', e);
  plmStore = null;
}

/**
 * PLM业务类
 */
class PlmBiz {

  /**
   * 获取PLM系统状态
   */
  static async getStatus() {
    let options = {
      title: '加载中...',
      hasLoading: true
    };
    
    try {
      const result = await cloudHelper.callCloudData('plm/status', {}, options);
      return result || null;
    } catch (e) {
      console.error('获取PLM状态失败', e);
      return null;
    }
  }
  
  /**
   * 获取PLM配置
   */
  static async getConfig() {
    // 检查缓存
    const cacheKey = 'PLM_CONFIG';
    let config = cacheHelper.get(cacheKey);
    if (config) return config;
    
    // 没有缓存则从云端获取
    let options = {
      hasLoading: false
    };
    
    try {
      const result = await cloudHelper.callCloudData('plm/config', {}, options);
      
      if (result) {
        // 设置缓存，有效期30分钟
        const cacheTime = 30 * 60;
        cacheHelper.set(cacheKey, result, cacheTime);
      }
      
      return result || null;
    } catch (e) {
      console.error('获取PLM配置失败', e);
      return null;
    }
  }
  
  /**
   * 获取用户在PLM系统中的角色
   */
  static async getUserRole() {
    let options = {
      hasLoading: false
    };
    
    try {
      const result = await cloudHelper.callCloudData('plm/user_role', {}, options);
      return result || null;
    } catch (e) {
      console.error('获取用户角色失败', e);
      return null;
    }
  }
  
  /**
   * 获取PLM通知消息
   */
  static async getNotifications(limit = 10) {
    let options = {
      hasLoading: false
    };
    
    try {
      const result = await cloudHelper.callCloudData('plm/notifications', { limit }, options);
      return result || [];
    } catch (e) {
      console.error('获取通知消息失败', e);
      return [];
    }
  }
  
  /**
   * 格式化项目信息用于显示
   * @param {Object} project 项目数据
   */
  static formatProjectForDisplay(project) {
    if (!project) return null;
    
    try {
      // 创建日期显示
      if (project.CREATETIME) {
        project.createTimeDesc = timeHelper.timestamp2Time(project.CREATETIME);
        project.createDateDesc = timeHelper.timestamp2Date(project.CREATETIME);
      }
      
      // 修改日期显示
      if (project.UPDATETIME) {
        project.updateTimeDesc = timeHelper.timestamp2Time(project.UPDATETIME);
        project.updateDateDesc = timeHelper.timestamp2Date(project.UPDATETIME);
      }
      
      // 状态文字化
      project.statusDesc = this.getProjectStatusDesc(project.status);
      
      // 计算项目时长
      if (project.startTime && project.endTime) {
        const startDate = timeHelper.time2Timestamp ? timeHelper.time2Timestamp(project.startTime) : new Date(project.startTime).getTime();
        const endDate = timeHelper.time2Timestamp ? timeHelper.time2Timestamp(project.endTime) : new Date(project.endTime).getTime();
        
        if (startDate && endDate) {
          const diffDays = Math.floor((endDate - startDate) / (24 * 3600 * 1000));
          project.durationDays = diffDays > 0 ? diffDays : 0;
        }
      }
      
      return project;
    } catch (e) {
      console.error('格式化项目信息失败', e);
      return project;
    }
  }
  
  /**
   * 获取项目状态描述
   * @param {number} statusCode 状态码
   */
  static getProjectStatusDesc(statusCode) {
    const statusMap = {
      1: '待立项',
      2: '已立项',
      3: '设计中',
      4: '开发中',
      5: '测试中',
      6: '已完成',
      7: '已交付',
      99: '已取消'
    };
    
    return statusMap[statusCode] || '未知状态';
  }
  
  /**
   * 获取快速访问项目列表
   */
  static async getQuickAccessProjects() {
    // 先从缓存获取
    const cacheKey = 'PLM_QUICK_ACCESS';
    let projects = cacheHelper.get(cacheKey);
    if (projects) return projects;
    
    // 从云端获取
    let options = {
      hasLoading: false
    };
    
    try {
      const result = await cloudHelper.callCloudData('plm/quick_access', {}, options);
      
      if (result && Array.isArray(result)) {
        // 设置缓存
        cacheHelper.set(cacheKey, result, 10 * 60); // 10分钟
        return result;
      }
      
      return [];
    } catch (e) {
      console.error('获取快速访问项目失败', e);
      return [];
    }
  }
}

module.exports = PlmBiz; 